package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"gorm.io/gorm"
	"ratil/models"
)

type StoreController struct {
	beego.Controller
}

type JsonMsg struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *StoreController) Add() {
	name := c.GetString("name")
	address := c.GetString("address")
	price, _ := c.GetFloat("price", 64)
	store := models.Store{
		Name:    name,
		Address: address,
		Price:   price,
	}
	err := models.DB.Create(&store).Error
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *StoreController) List() {
	var sotre []models.Store
	err := models.DB.Find(&sotre).Error
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "展示成功",
			Data: sotre,
		}
		c.ServeJSON()
	}
}
func (c *StoreController) Update() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	address := c.GetString("address")
	price, _ := c.GetFloat("price", 64)
	store := models.Store{
		Model:   gorm.Model{ID: uint(id)},
		Name:    name,
		Address: address,
		Price:   price,
	}
	err := models.DB.Updates(&store).Error
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "修该失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
